package cn.lysj.framework.order.util.wx;

import cn.lysj.framework.order.dto.PayParam;
import lombok.extern.slf4j.Slf4j;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信公众号操作相关工具类
 */
@Slf4j
public class WxPublicUtil {




    /**
     * @author zk  
     * @date 2018/3/29 10:41
     * @Description 修正后的统一获取prepayId的方法
     */  
    public static String getPrepayId(PayParam model){

        Map<String, String> paramMap = UnifiedOrderUtil.createMap(model);
        paramMap.put("sign", UnifiedOrderUtil.sign(paramMap,model.getAppKey()));
        String xml = UnifiedOrderUtil.createXml(paramMap);
        return UnifiedOrderUtil.sendPrePay(xml);
    }


    public static Map<String, String> xmlToMap(String strXML) throws Exception {
        Map<String, String> data = new HashMap();
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
        Document doc = documentBuilder.parse(stream);
        doc.getDocumentElement().normalize();
        NodeList nodeList = doc.getDocumentElement().getChildNodes();

        for(int idx = 0; idx < nodeList.getLength(); ++idx) {
            Node node = nodeList.item(idx);
            if (node.getNodeType() == 1) {
                Element element = (Element)node;
                data.put(element.getNodeName(), element.getTextContent());
            }
        }

        try {
            stream.close();
        } catch (Exception var10) {
        }

        return data;
    }

}
